package com.attilax.sql;

import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSONObject;
import com.attilax.io.filex;
import com.attilax.ioc.Ioc4wash;
import com.attilax.lang.MapX;
import com.attilax.user.UserSync4jonlye;
import com.google.common.collect.Maps;
import com.google.inject.Inject;
@SuppressWarnings("all")
public class Sqlbuilder extends Dsl2sqlServiceV2 {
	@Inject
	DbMetaService DbMetaSvr1;

	Map filedMap; // jsonKey => tableCol
	
	public static void main(String[] args) {
		//{name=沈闯, department=信息化部}
		Sqlbuilder c = Ioc4wash.getBean(Sqlbuilder.class);
		Map req_flted=Maps.newConcurrentMap();
		req_flted.put("member_no", 1);
		System.out.println(c.toInsertSql(req_flted, "s_member") );
	//	System.out.println(c.getInsertSql("s_member", m, ""));
	}

	public String build(JSONObject jo1, String filedMapTable, String sqlType, String tableName, String dblibname) {
	
		Map m = getTabCol_kvMap(jo1, filedMapTable);
		if(sqlType.equals("insert"))
		{
			return getInsertSql(tableName,m,dblibname);
		}
		return dblibname;
		
	}
@Deprecated
	private String getInsertSql(String tableName, Map m, String dblibname) {
	String insertFields=get_insertFields(m);
	String insertVals=getInsertVals(m,tableName,dblibname);
	
		String sql = "insert "+tableName+" (@fld@)values(@val@)";
		sql=sql.replaceAll("@fld@", insertFields);
		sql=sql.replaceAll("@val@", insertVals);
		return  sql;
	}
	
	//r327 for
		public String toInsertSql(Map req_flted, String table) {
			
			// = getTable(req);
//			Map req_flted = fltMap(req, table);
			if(req_flted.keySet().size()==0)
				throw new RuntimeException("req_flted field is empty ");
		//	calc_cols4sql_n_valsArr(req_flted);
		   prikey = metaSvr.getPrimaryKey(table);
		 	  ColumnsDefs=  metaSvr.getColumns(null, table);
			SqlKvUtil sqlKvUtil = new SqlKvUtil();
			sqlKvUtil.prikey=prikey;
			sqlKvUtil.ColumnsDefs=ColumnsDefs;
			String[] a=sqlKvUtil.toInsertSqlKVPart(req_flted);
			String sql = "insert into @tab@(@cols@)values(@vals@)";
			sql = sql.replace("@tab@", table);
			sql = sql.replace("@cols@", a[0]);
			sql = sql.replace("@vals@", a[1]);
			return sql;

		}
		private Map fltMap(Map req, String table) {
			reqMap=req;
//			List<Map> li = metaSvr.getColumns(table);
//			
//			for (Map col_map : li) {
//				colTypeMap.put(col_map.get("COLUMN_NAME") , col_map.get("TYPE_NAME"));
//			//	colTypeMap.put("TYPE_NAME", );
//			}
			Set<String> cols = metaSvr.getColumns_set(table);

//			try {
//				String line="table:"+table+"  getColumns_size:"+li.size()+"  cols_size:"+cols.size();
//				filex.saveLog(line, "e:\\logQ4_fltMap");
//			} catch (Exception e) {
//				System.out.println("--fltMap:"+e.getMessage());
//			}
		
			Map ret = MapX.reduce_onlyRemainDbColsKey(req, cols);
			return ret;
		}
		
		private Map fltMap_hiperf(Map req, String table) {
			reqMap=req;
//			List<Map> li = metaSvr.getColumns(table);
//			
//			for (Map col_map : li) {
//				colTypeMap.put(col_map.get("COLUMN_NAME") , col_map.get("TYPE_NAME"));
//			//	colTypeMap.put("TYPE_NAME", );
//			}
			Set<String> cols = metaSvr.getColumns_set_fromLi(ColumnsDefs);

//			try {
//				String line="table:"+table+"  getColumns_size:"+li.size()+"  cols_size:"+cols.size();
//				filex.saveLog(line, "e:\\logQ4_fltMap");
//			} catch (Exception e) {
//				System.out.println("--fltMap:"+e.getMessage());
//			}
		
			Map ret = MapX.reduce_onlyRemainDbColsKey(req, cols);
			return ret;
		}
		
	public String toInsertSql_hiPerf(Map map, String table) {
			
 
			if(map.keySet().size()==0)
				throw new RuntimeException("req_flted field is empty ");
			
			Map	fltedMap=fltMap_hiperf(map,table);
		
			SqlKvUtil sqlKvUtil = new SqlKvUtil();
			sqlKvUtil.prikey=prikey;
			sqlKvUtil.ColumnsDefs=ColumnsDefs;
			String[] a=sqlKvUtil.toInsertSqlKVPart(map);
			String sql = "insert into @tab@(@cols@)values(@vals@)";
			sql = sql.replace("@tab@", table);
			sql = sql.replace("@cols@", a[0]);
			sql = sql.replace("@vals@", a[1]);
			return sql;

		}

	private String getInsertVals(Map m, String tableName, String dblibname) {
		// TODO Auto-generated method stub
		return null;
	}

	private String get_insertFields(Map m) {
		// TODO Auto-generated method stub
		return null;
	}

	private Map getTabCol_kvMap(JSONObject jo1, String filedMapTable) {
		filedMap = get_filedMap(filedMapTable);

		Set<String> st = filedMap.keySet();

		Map Tab_filed_kv_Map = Maps.newConcurrentMap();
		for (String jsonKey : st) {
			Object jsonV = jo1.get(jsonKey);
			String tabCol = (String) filedMap.get(jsonKey);
			Tab_filed_kv_Map.put(tabCol, jsonV);
		}

		return Tab_filed_kv_Map;
	}

	private Map get_filedMap(String filedMapTable) {
		filedMapTable = filedMapTable.trim();
		String[] items = filedMapTable.split(",");
		Map m = Maps.newConcurrentMap();
		for (String item : items) {
			String[] kv_a = item.split(":");
			m.put(kv_a[0].trim(), kv_a[1]);
		}

		return m;
	}

	public String build(Map m, String type, String tab) {
	 
		return  toInsertSql(m, tab) ;
	}

	public String toMergeSql_hiPerf(Map map, String table, String mergeExt) {
		if(map.keySet().size()==0)
			throw new RuntimeException("req_flted field is empty ");
		
		Map	fltedMap=fltMap_hiperf(map,table);
	
		SqlKvUtil sqlKvUtil = new SqlKvUtil();
		sqlKvUtil.prikey=prikey;
		sqlKvUtil.ColumnsDefs=ColumnsDefs;
		String[] a=sqlKvUtil.toInsertSqlKVPart(map);
		String sql = "insert into @tab@(@cols@)values(@vals@) "+mergeExt;
		sql = sql.replace("@tab@", table);
		sql = sql.replace("@cols@", a[0]);
		sql = sql.replace("@vals@", a[1]);
		return sql;
	}

	public String getMergeUpdateExpress(String cols) {
		String pre="ON DUPLICATE KEY UPDATE ";
		String tmpl="@col@=VALUES(@col@)";
		  
		String[] col_arr=cols.trim().split(",");
		int n=0;
		for (String col : col_arr) {
			n++;
			if(n==1)
				pre+=tmpl.replaceAll("@col@", col);
			else
			pre+=","+tmpl.replaceAll("@col@", col);
		}
	
		
			//	,duties_id=VALUES(duties_id),duties_name=VALUES(duties_name),"
		return pre;
	}

	public String toQuerySql(Map m_jsondsl) {
		String sql = "select @fld@ from @tab@ ";
		sql = sql.replace("@tab@", m_jsondsl.get("storePosition").toString());
		sql = sql.replace("@fld@", m_jsondsl.get("queryProp").toString());

		if (m_jsondsl.get("condition") != null)
			sql += " where " + m_jsondsl.get("condition");
		if (m_jsondsl.get("orderby") != null)
			sql += " order by " + m_jsondsl.get("orderby");
		if (m_jsondsl.get("page") != null) {
			Integer pagesize = Integer.parseInt(m_jsondsl.get("pagesize").toString());
			int page = Integer.parseInt(m_jsondsl.get("page").toString());
			Integer offset = (page - 1) * pagesize;
			sql += "  limit " + offset.toString() + "," + pagesize.toString();
		}
		return sql;
	}

}
